#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    vector<int> solve(vector<int>& a) {
        stack<int> st;
        vector<int> ret, table(a.size());
        for (int i = a.size() - 2; i >= 0; i--)
            table[i] = max(a[i + 1], table[i + 1]);
        int ma = a.size();
        for (int i = 0; i < a.size(); i++)
        {
            if (a[i] == ma)
            {
                ret.push_back(a[i]);
                ma = table[i];
                while (st.size())
                {
                    int top = st.top();
                    if (top > table[i])
                    {
                        ret.push_back(top);
                        st.pop();
                    }
                    else break;
                }
            }
            else
            {
                st.push(a[i]);
            }
        }
        while (st.size())
        {
            ret.push_back(st.top());
            st.pop();
        }
        return ret;
    }
};